package com.huitone.smspfm.core.filter;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.huitone.smspfm.logger.ExtLogger;
import org.springframework.data.redis.connection.RedisConnection;

import com.bin.common.utils.DateTimeUtils;
import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.core.config.AppStaticConfigs;
import com.huitone.smspfm.core.constant.DealResult;
import com.huitone.smspfm.core.waterpipe.client.impl.SimpleGateLink;
import com.huitone.smspfm.dao.oracle.entity.GateDef;
import com.huitone.smspfm.dao.oracle.entity.MoIns;
import com.huitone.smspfm.dao.oracle.entity.SvrNodeDef;
import com.huitone.smspfm.redis.model.AppCanstant;
import com.huitone.smspfm.redis.model.SmsEntity;
import com.huitone.smspfm.redis.pipeline.PipelineOpts.ABExcuteCommands;

/**   
* @Title AddBlackUserFilterTask.java 
* @Package com.huitone.smspfm.core.filter 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年7月9日 下午3:23:14 
* @version V1.0   
*/
public class MoDesitinationMatchFilterTask extends Thread {
	
	private ExtLogger logger = ExtLogger.create(MoDesitinationMatchFilterTask.class);
	
	private String moduleName = "上行短信目的地匹配模块";
	
	private byte[] moduleNameB = AppStaticConfigs.stringRedisSerializer.serialize(moduleName); 
	
	private List<SmsEntity> entities = null;
	
	public MoDesitinationMatchFilterTask(List<SmsEntity> entities) {
		this.entities = entities;
	}

	@Override
	public void run() {
		
		if (entities == null) return;
		
		AppStaticConfigs.pipelineOpts3.save(new ABExcuteCommands() {

			@Override
			public void excute(RedisConnection connection) {
				
				for (int n = 0 ; n < entities.size() ; n ++) {
					
					SmsEntity entity = entities.get(n);
					
					if (entity.isExists()) {
						
						Map<byte[], byte[]> hashMap = new HashMap<>();
						hashMap.put(AppCanstant.SmsEntity.DealModuleName, moduleNameB);
						hashMap.put(AppCanstant.SmsEntity.SdealTime, AppStaticConfigs.stringRedisSerializer.serialize(DateTimeUtils.dateToStr2(new Date())));
						
						String seqNum = entity.getSequence() + ":" + entity.getUser();
						String smInfo = "SMInfo:" + seqNum;
						String sendport = StringUtils.toString(entity.getSendport());
						String content = StringUtils.toString(entity.getSmcont());
						String spNumber = "";
						boolean spMatched = true;
						boolean spFromSdef = true;
						GateDef gateDef = null;
						
						SimpleGateLink gateLink = (SimpleGateLink)AppStaticConfigs.simpleGateLinkRegister.get(StringUtils.toString(entity.getGateLinkId()));
						
						if (gateLink != null) {
							gateDef = gateLink.getGateDef();
							spNumber = StringUtils.toString(gateDef.getSpNumber());
						}
						
						if (StringUtils.startsWith(sendport, spNumber)) {//sendport是否包含了sp号
							
							String srvNode = null;
							String orgSrvNode = null;
							String recId = null;
							
							// 端口号匹配
							String extCode = StringUtils.substringAfter(sendport, spNumber); // 剔除sendport中的sp号码得出扩展码
							int length = extCode.length();
							
							for (int i = length ; i > 0 ; i --) {
								String tmpExtCode = StringUtils.substring(extCode, 0, i);
								// 查找业务端定义表
								for (SvrNodeDef sndf : AppStaticConfigs.configSvrNodeDefList) {
									if (StringUtils.equals(tmpExtCode, sndf.getSendPort())) {
										srvNode = sndf.getSvrNode();
										orgSrvNode = sndf.getSvrNode();
										recId = sndf.getSvrNode();
										break;
									}
								}
							}
							
							if (StringUtils.isEmpty(srvNode)) {
								for (int i = length ; i > 0 ; i --) {
									String tmpExtCode = StringUtils.substring(extCode, 0, i);
									// 查找上行短信匹配表
									for (MoIns moIns : AppStaticConfigs.configMoInsList) {
										if (StringUtils.equals(tmpExtCode, moIns.getSendport())) {
											srvNode = moIns.getSvrNode();
											orgSrvNode = moIns.getOrgSvrNode();
											recId = moIns.getRecId();
											spFromSdef = false;
											break;
										}
									}
								}
							}
							
							// 端口号没有匹配到则进行内容匹配
							if (StringUtils.isEmpty(srvNode)) {
								
								for (MoIns moIns : AppStaticConfigs.configMoInsList) {
									if (isMatch(content, moIns.getSmPattern())) {
										srvNode = moIns.getSvrNode();
										orgSrvNode = moIns.getOrgSvrNode();
										recId = moIns.getRecId();
										spMatched = false;
										break;
									}
								}
							}
							
							Date endTime = new Date();
							
							if (!StringUtils.isEmpty(srvNode)) {
								
								hashMap.put(AppCanstant.SmsEntity.EdealTime, AppStaticConfigs.stringRedisSerializer.serialize(DateTimeUtils.dateToStr2(endTime)));
								hashMap.put(AppCanstant.SmsEntity.DealResult, DealResult.RESULT0B);
								hashMap.put(AppCanstant.SmsEntity.DealResultDesc, DealResult.RESULT0_DESCB);
								hashMap.put(AppCanstant.SmsEntity.Srv_node, AppStaticConfigs.stringRedisSerializer.serialize(StringUtils.toString(srvNode)));
								hashMap.put(AppCanstant.SmsEntity.OrgSrvNode, AppStaticConfigs.stringRedisSerializer.serialize(StringUtils.toString(orgSrvNode)));
								hashMap.put(AppCanstant.SmsEntity.SendPort, AppStaticConfigs.stringRedisSerializer.serialize(StringUtils.toString(extCode)));
								
								
								connection.hMSet(AppStaticConfigs.stringRedisSerializer.serialize(smInfo), hashMap);
								
								connection.lPush(AppStaticConfigs.iSMMoDealListB, AppStaticConfigs.stringRedisSerializer.serialize(seqNum));
								
								logger.moprocc("[序列号:用户号码][" + seqNum + "]匹配到目的地,对应业务端编号是:" + srvNode + ",匹配方式:" + (spMatched ? ((spFromSdef ? "业务端定义表" : "上行短信匹配表") + "发送端口号匹配"):"内容匹配") + ",匹配规则ID:" + recId);
								
							} else {
								
								hashMap.put(AppCanstant.SmsEntity.EdealTime, AppStaticConfigs.stringRedisSerializer.serialize(DateTimeUtils.dateToStr2(endTime)));
								hashMap.put(AppCanstant.SmsEntity.DealResult, DealResult.RESULT1B);
								hashMap.put(AppCanstant.SmsEntity.DealResultDesc, AppStaticConfigs.stringRedisSerializer.serialize("业务端号为空"));
								
								connection.hMSet(AppStaticConfigs.stringRedisSerializer.serialize(smInfo), hashMap);
								
								//connection.lPush(AppStaticConfigs.iSMMoDealListB, AppStaticConfigs.stringRedisSerializer.serialize(seqNum));
								
								connection.lPush(AppStaticConfigs.iSMMoEndListB, AppStaticConfigs.stringRedisSerializer.serialize(seqNum));
								
								logger.mowarn("[序列号:用户号码][" + seqNum + "]没有匹配到目的业务端号,上行短信内容:" + entity.toString());
							}
							
						} else {
							
							Date endTime = new Date();
							
							hashMap.put(AppCanstant.SmsEntity.EdealTime, AppStaticConfigs.stringRedisSerializer.serialize(DateTimeUtils.dateToStr2(endTime)));
							hashMap.put(AppCanstant.SmsEntity.DealResult, DealResult.RESULT1B);
							hashMap.put(AppCanstant.SmsEntity.DealResultDesc, AppStaticConfigs.stringRedisSerializer.serialize("端口号SendPort中的SP号码和网关通道的SP号码不匹配"));
							
							connection.hMSet(AppStaticConfigs.stringRedisSerializer.serialize(smInfo), hashMap);
							
							//connection.lPush(AppStaticConfigs.iSMMoDealListB, AppStaticConfigs.stringRedisSerializer.serialize(seqNum));
							
							connection.lPush(AppStaticConfigs.iSMMoEndListB, AppStaticConfigs.stringRedisSerializer.serialize(seqNum));
							
							logger.mowarn("端口号SendPort中的SP号码和网关通道的SP号码不匹配,网关信息:" + (gateDef != null ? gateDef.toString():"GateDef=null") + ",上行短信:" + entity.toString());
						}
					}
				}
			}
		});
	}
	
	public boolean isMatch(String input, String regex) {
		
		if (StringUtils.isEmpty(input) || StringUtils.isEmpty(regex)) return false;
		
		regex = StringUtils.replace(regex, "*", ".*");
		
		Pattern p = Pattern.compile(regex);
		
		Matcher m = p.matcher(input);
		
		return m.matches();
	}

}
